#!/usr/bin/python
#-*-coding:utf-8-*-

from util.parse import iniParse
from manager.manager import manager
from util.file import file
import os,sys,signal

def log(msg = None,isEnd = True):
    global masterSig,masterPid
    print '%s # [PID:%d] >>> %s' % (masterSig,masterPid,msg)
    if isEnd is True:
        quit()
def run(obj,name,param):
    info = obj.enableTask(name,param,'Working-'+name,os.getpid())
    if info is False:
        stop(name)
def stop(name = None):
    try:
        fileObj = file()
        filename= name+'.pid'
        pid = fileObj.read(filename)
        log('即将杀死进程: %s, 并删除锁文件: %s , 请按CTRL+C 结束窗口。' % (pid,fileObj.path+filename))
        if pid:
            os.remove(fileObj.path+filename)
            res = os.kill(int(pid),signal.SIGKILL)
    finally:
        quit()        
def start(name=None):
    global conf
    app = conf.get(name)
    pid = os.fork()
    if pid == 0:
        run(manager(),name,app)
    else:    
        file().create(name+'.pid',str(pid))
        log('应用 %s 子进程已建立,PID: %d ,并已建立锁文件。' % (name,pid) ,False)
def main():
    global args,conf
    if len(args) > 2:
        cmd = args[1]
        app = args[2]
        if cmd not in ['start','stop','restart']:
            log('执行命令错误,必须是[start/stop/restart]')
        if conf.initialize.has_section(app):
            eval(cmd)(app)
        else:
            log('未能找到 %s 配置信息' % app)
    else:
        log('参数错误,请使用: python main.py start appname')
if __name__ == "__main__":
    masterPid = os.getpid()
    masterSig = 'Master'
    args = sys.argv
    conf = iniParse()
    try:
        main()
    except Exception as e:
        log('进程异常: %s' % e.message)
        quit()